package com.servlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 数据压缩的基本原理：
 * 1.源数据
 * 2.ByteArrayOutputStream字节数据流
 * 3.GZIPOutputStream字节压缩流
 * new GZIPOutputStream时把ByteArrayOutputStream放进去，然后GZIPOutputStream写数据，即写到字节数组中，然后字节数组再输出来
 */
@WebServlet(name="FirstServlet",urlPatterns="/FirstServlet")
public class FirstServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		
		String str="hncu河南郑州hncu河南郑州hncu河南郑州hncu河南郑州hncu河南郑州hncu河南郑州hncu河南郑州hncu河南郑州";
/*		System.out.println("压缩前(utf-8字节数组):"+str.getBytes("utf-8").length);
		System.out.println("压缩前(默认字节数组):"+str.getBytes().length);
		
		//压缩输出：把源数据通过GZIPOutputStream压缩到ByteArrayOutputStream中
		ByteArrayOutputStream baout=new ByteArrayOutputStream();
		GZIPOutputStream gzip=new GZIPOutputStream(baout);
		gzip.write(str.getBytes("utf-8"));
		gzip.close();
		
		//从baout中内存流中把压缩后的数据取出来，然后输出到客户端
		byte[] dest=baout.toByteArray();
		System.out.println("压缩后:"+dest.length);
		
		//在输出之前要告诉客户端数据是gzip格式
		response.setHeader("Content-Encoding", "gzip");
		response.setContentLength(dest.length);
		response.getOutputStream().write(dest);*/
		//response.getWriter().write(str);
		response.getOutputStream().write(str.getBytes());
	}
}
